package com.wang.user.service.user;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.wang.constant.AppConstant;
import com.wang.exception.BusinessException;
import com.wang.reponse.WeChatMiniAuthorizeVo;
import com.wang.user.component.RestTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class WechatNewServiceImpl implements WechatNewService{

    @Autowired
    private RestTemplateUtil restTemplateUtil;

    /**
     * 小程序登录凭证校验
     * @return 小程序登录校验对象
     */
    @Override
    public WeChatMiniAuthorizeVo miniAuthCode(String code) {
        String appId = AppConstant.AppId;

        String secret = AppConstant.AppSecret;

        String url = StrUtil.format(AppConstant.WECHAT_MINI_SNS_AUTH_CODE2SESSION_URL, appId, secret, code);
        JSONObject data = restTemplateUtil.getData(url);
        if (ObjectUtil.isNull(data)) {
            throw new BusinessException("微信平台接口异常，没任何数据返回！");
        }
        if (data.containsKey("errcode") && !data.getString("errcode").equals("0")) {
            if (data.containsKey("errmsg")) {
                // 保存到微信异常表
                log.error("微信小程序登录凭证校验异常：{}", JSONUtil.toJsonStr(data));
                throw new BusinessException("微信接口调用失败：" + data.getString("errcode") + data.getString("errmsg"));
            }
        }
        return JSONObject.parseObject(data.toJSONString(), WeChatMiniAuthorizeVo.class);
    }
}
